import React from 'react';
import {browserHistory,Link} from 'react-router';
import { Form, Button, Input, Select, message, Modal,InputNumber } from 'antd';
import $ from 'jquery';
import config from '../../../config/config';
const allRouter=config.router;
const FormItem = Form.Item;
const Option = Select.Option;
const token = sessionStorage.getItem('token');
class AddFirstDepartment extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            justDoctorList:[],//员工列表
            departmentList:[],//员工对应科室分类
            choseDoctorName:'',//选择的医生名字，后台要求传
            editDoctor:{},//正在编辑的医生信息
            hasNamed:false,//该科室该医生下的挂号费是否已经设置
        };
        this.saveData = this.saveData.bind(this);
        this.cancelSave = this.cancelSave.bind(this);
    }
    componentWillMount() {
        //获取员工列表
        this.getEmployeeList();
    }
    componentDidMount() {
        //如果为编辑状态
        if(this.props.params.feeId !== "0"){

            console.log("edit");
            let url=allRouter.patientOrigin+'/registration/one/'+this.props.params.feeId;
            $.ajax({
                url:url,
                type: "GET",
                async: true,
                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                success:data=>{
                    let docInfo=data.registration;

                    let url=allRouter.patientOrigin+'/doctor/list';
                    $.ajax({
                        url:url,
                        type: "get",
                        async: true,
                        headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                        success:data=>{
                            console.log(data);
                            if(data.code===200){
                                //给列表每一项增加索引
                                let doctorList=[];
                                if (data.users.length > 0) {
                                    data.users.forEach((ele, i) => {
                                        ele.index= i + 1;
                                        if(ele.role==='医生'){
                                            doctorList.push(ele);
                                        }
                                    });
                                }
                                doctorList.map(item=>{
                                    if(item._id===docInfo.doctorid){
                                        this.setState({
                                            departmentList:item.department,
                                            choseDoctorName:item.name
                                        },()=>{
                                            if(data.code===200){
                                                this.setState({
                                                    editDoctor:docInfo
                                                },()=>{
                                                    this.props.form.setFieldsValue({
                                                        doctorName:docInfo.doctorname,
                                                        departmentName:docInfo.department,
                                                        registrationFee:docInfo.price,
                                                        doctorAttribution:docInfo.level,
                                                    });
                                                })
                                            }else{
                                                console.log("获取挂号费来源名称出错");
                                            }
                                        })
                                    }
                                })

                            }else{
                                console.log("获取员工列表出错");
                            }
                        },
                        error:err=>{
                            console.log(err);
                        }
                    });
                },
                error:err=>{
                    console.log(err);
                }
            });
        }
    }
    //获取角色为医生的员工列表
    getEmployeeList() {
        console.log(1);
        let url=allRouter.patientOrigin+'/doctor/list';
        $.ajax({
            url:url,
            type: "get",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            success:data=>{
                console.log(data);
                if(data.code===200){
                    //给列表每一项增加索引
                    let doctorList=[];
                    if (data.users.length > 0) {
                        data.users.forEach((ele, i) => {
                            ele.index= i + 1;
                            if(ele.role==='医生'){
                                doctorList.push(ele);
                            }
                        });
                    }
                   // console.log(data);
                    this.setState({
                        justDoctorList:doctorList
                    },()=>{
                        console.log(this.state.justDoctorList);
                    })
                }else{
                    console.log("获取员工列表出错");
                }
            },
            error:err=>{
                console.log(err);
            }
        })
    }

    //保存科室
    saveData(){
        this.props.form.validateFields((err,values)=> {
            console.log(values);
            if(err){
                return;
            }
            if(this.state.hasNamed){
                message.error('该科室该医生挂号费已经设置!',1);
                return;
            }
            //即是编辑状态  无状态更新 不能修改密码，不传密码,需要传递ID
            if(this.props.params.feeId != "0"){
                let url=allRouter.patientOrigin+'/registration/update';
                // console.log(url);
                $.ajax({
                    url: url,
                    type: "post",
                    async: true,
                    traditional: true,
                    headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                    data: {
                        department:values.departmentName,
                        price:values.registrationFee,
                        level:values.doctorAttribution,
                        id:this.props.params.feeId,
                    },
                    success:data => {
                        console.log(data);
                        if(data.code===200){
                            message.info('挂号费信息修改成功',);
                            browserHistory.push('registrationFeeManage');
                        } else{
                            message.info('员工信息修改失败');
                        }
                    },
                    error:err=>{
                        console.log(err);
                    }
                });
                return;
            }
            let url=allRouter.patientOrigin+'/registration/save';
            $.ajax({
                url: url,
                type: "post",
                async: true,
                traditional: true,
                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                data: {
                    department:values.departmentName,
                    doctorid:values.doctorName,
                    doctorname:this.state.choseDoctorName,
                    price:values.registrationFee,
                    level:values.doctorAttribution,
                    state:'启用'
                },
                success:data => {
                    console.log(data);
                    if(data.code===200){
                        message.info('挂号费增加成功',);
                        this.props.form.setFieldsValue({
                            departmentName:undefined,
                            registrationFee:undefined,
                            doctorAttribution:undefined,
                        });
                    }else{
                        message.info('挂号费增加失败');
                    }
                },
                error:err=>{
                    console.log(err);
                }
            });
        })
    }
    //取消保存
    cancelSave(){
        Modal.confirm({
            title:'取消保存',
            content:'确认取消保存并返回医生挂号费列表页面吗？',
            onCancel:()=>{
                //console.log('取消')
            },
            onOk:()=>{
                browserHistory.push('registrationFeeManage');
            }
        })
    }

    //选择医生，切换科室
    handleDoctorChange(value){
        console.log(value);
        this.state.justDoctorList.map(item=>{
            if(item._id===value){
                this.setState({
                    departmentList:item.department,
                    choseDoctorName:item.name
                },()=>{
                    console.log(this.state.departmentList);
                });
                this.props.form.setFieldsValue({
                    departmentName:''
                })
            }
        });

        const form = this.props.form;
        // console.log(value);
        // console.log(form.getFieldValue('doctorName'))
        let url=allRouter.patientOrigin+'/registration/hadregister';
        $.ajax({
            url: url,
            type: "post",
            async: true,
            traditional: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            data: {
                department:value,
                doctorid:form.getFieldValue('departmentName')
            },
            success:data => {
                console.log(data);
                if(data.code===201){
                    this.props.form.setFields({
                        doctorName: { value: value,errors: [new Error(data.mes)] }
                    })
                }
            },
            error:err=>{
                console.log(err);
            }
        });

    }
    //验证医生和科室重名
    checkDoctorDepartment(value){
        const form = this.props.form;
       // console.log(value);
       // console.log(form.getFieldValue('doctorName'))
            let url=allRouter.patientOrigin+'/registration/hadregister';
            $.ajax({
                url: url,
                type: "post",
                async: true,
                traditional: true,
                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                data: {
                    department:value,
                    doctorid:form.getFieldValue('doctorName')
                },
                success:data => {
                    console.log(data);
                    if(data.code===201){
                        this.props.form.setFields({
                            departmentName: { value: value,errors: [new Error(data.mes)] }
                        });
                        this.setState({
                            hasNamed:true,
                        })
                    }else{
                        this.setState({
                            hasNamed:false,
                        })
                    }
                },
                error:err=>{
                    console.log(err);
                }
            });


    }
    render() {
        const formItemLayout = { labelCol: { span: 2 }, wrapperCol: { span: 18 } };
        const { getFieldDecorator } = this.props.form;
        return (
            <div className='container'>
                <div className='add-department-box'>
                    <div className="show-template">
                        <span>*{this.props.params.feeId != "0"?"编辑":"新增"}挂号</span>
                    </div>
                    <div className='storeRow'>
                        <FormItem {...formItemLayout} label="选择医生" style={{ display: 'inline-block', width: '100%' }} >
                            {getFieldDecorator('doctorName', {
                                rules: [{ required: true, message: '选择医生不能为空' }],
                            })(
                                <Select style={{ width: '100% '}} placeholder="请选择医生" onChange={this.handleDoctorChange.bind(this)}>
                                    {this.props.params.feeId != "0"?<Option value={this.state.editDoctor.doctorid} key={this.state.editDoctor.doctorid}>{this.state.justDoctorList.doctorname}</Option>:this.state.justDoctorList.map(item=>{
                                        return <Option value={item._id} key={item._id}>{item.name+"-"+item.phone.slice(-4)}</Option>
                                    })}
                                </Select>
                            )}
                        </FormItem>
                    </div>
                    <div className='storeRow'>
                        <FormItem {...formItemLayout} label="科室名称" style={{ display: 'inline-block', width: '100%' }} >
                            {getFieldDecorator('departmentName', {
                                rules: [{ required: true, message: '科室名称不能为空' }],

                            })(
                                <Select style={{ width: '100% '}} placeholder="请选择科室" onChange={this.checkDoctorDepartment.bind(this)}>
                                    {this.state.departmentList.map(item=> {
                                        if(item){ return <Option value={item._id} key={item._id}>{item.name}</Option>}}
                                      )
                                    }
                                </Select>
                            )}
                        </FormItem>
                    </div>
                    <div className='storeRow' >
                        <FormItem {...formItemLayout} label="挂号费" style={{ display: 'inline-block', width: '100%' }} >
                            <div style={{display:'flex'}}>
                            {getFieldDecorator('registrationFee', {
                                rules: [{ required: true, message: '挂号费不能为空' }],
                            })(
                                    <InputNumber placeholder="请输入挂号费" step={1} min={0} style={{ width: '100%' }} precision={0}/>
                            )}
                            <span>元</span>
                            </div>
                        </FormItem>
                    </div>
                    <div className='storeRow'>
                        <FormItem {...formItemLayout} label="医生属性" style={{ display: 'inline-block', width: '100%' }} >
                            {getFieldDecorator('doctorAttribution', {
                                rules: [{ required: true, message: '选择医生属性不能为空' }],

                            })(
                                <Select style={{ width: '100% '}} placeholder="请选择">
                                    <Option value="专家号">专家号</Option>
                                    <Option value="普通号">普通号</Option>
                                </Select>
                            )}
                        </FormItem>
                    </div>
                    <div style={{maxWidth:800,textAlign:'right',marginTop:10}}>
                        <Button type='primary' style={{marginRight:15}} onClick={this.saveData}>确定</Button>
                        <Button onClick={this.cancelSave}>取消</Button>
                    </div>
                </div>
            </div>
        )
    }
}
const AddFirstDepartmentForm = Form.create()(AddFirstDepartment);
export default AddFirstDepartmentForm;